package control;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.mysql.jdbc.Statement;
import database.database;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import memory.ChatBox;
import memory.Container;
import memory.User;

/**
 *
 * @author Didik
 */
public class Login extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            System.out.println("MySQL Connect Example.");
            database db = new database();

            String username = "";
            String userpass = "";
            String strQuery = "";
            Statement st = null;
            ResultSet rs = null;
            HttpSession session = request.getSession(true);

            try {
                db.createConnection();
                if (request.getParameter("username") != null && request.getParameter("username") != "" && request.getParameter("password") != null && request.getParameter("password") != "") {
                    username = request.getParameter("username").toString();
                    userpass = database.convert_md5(request.getParameter("password").toString());

                    strQuery = "select * from userdb where username='" + username + "' and  password='" + userpass + "'";
                    db.select(strQuery);
                    rs = db.getResultSet();
                    String nextJSP = "";
                    while (rs.next()) {
                        User user = new User(rs.getString("name"), rs.getString("username"), rs.getString("role"), System.currentTimeMillis());
                        session.setAttribute("user", user);
                        session.setAttribute("chatbox", new ChatBox());
                        session.setAttribute("loginuser", rs.getString("username"));
                        session.setAttribute("role", rs.getString("role"));
                        session.setAttribute("conn", db.getConnect());
                        getServletContext().setAttribute("sessionid", session.getId());
                        memory.Container cont = (memory.Container) getServletContext().getAttribute("cont");
                        cont.getOnlineuserlist().add(user);
                        //getServletContext().setAttribute("cont", cont);
                        if (rs.getString("role").toString().equalsIgnoreCase("admin")) {
                            nextJSP = "/Page?page=admin";
                        } else {
                            nextJSP = "Page?page=chat";
                            session.setAttribute("page", "chat");
                        }
                    }
                    if (nextJSP.equalsIgnoreCase("")) {
                        nextJSP = "Page?page=index";
                        request.setAttribute("feedback", "Invalid Username or Password!");
                    }
                    db.setLogin(username);
                    db.closeConnection();

                    response.sendRedirect(nextJSP);

                    //out.print(nextJSP);
                    //response.sendRedirect(nextJSP);
                    //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
                    //dispatcher.forward(request, response);
                } else {
                    String nextJSP = "/index.jsp";
                    request.setAttribute("feedback", "Invalid Username or Password!");
                    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
                    dispatcher.forward(request, response);
                }
            } catch (Exception e) {
                out.print(e);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
